package com.rigi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rigi.common.R;
import com.rigi.dto.DishDto;
import com.rigi.entity.Category;
import com.rigi.entity.Dish;
import com.rigi.entity.DishFlavor;
import com.rigi.service.CategoryService;
import com.rigi.service.DishFlavorService;
import com.rigi.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, String name) {
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        if (name != null) {
            wrapper.like("name", name);
        }
        wrapper.orderByDesc("update_time");
        dishService.page(dishPage, wrapper);

        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        List<Dish> dishList = dishPage.getRecords();

        List<DishDto> dishDtoList = dishList.stream().map(item -> {
            DishDto dishDto = new DishDto();
            Long categoryId = item.getCategoryId();
            if (categoryId != null) {
                Category category = categoryService.getById(categoryId);
                dishDto.setCategoryName(category.getName());
            }
            BeanUtils.copyProperties(item, dishDto);

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);
    }

    /**
     * 菜品添加
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {

        //清理redis缓存
        String key = "dish_" + dishDto.getCategoryId() + "_" + 1;
        redisTemplate.delete(key);

        dishService.saveWithFlavor(dishDto);
        return R.success("添加菜品成功");
    }

    /**
     * 更新回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 菜品跟新
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        //清理redis缓存
        String key = "dish_" + dishDto.getCategoryId() + "_" + 1;
        redisTemplate.delete(key);

        dishService.updateWithFlavor(dishDto);
        return R.success("更新成功");
    }

    /**
     * 停售/启售菜品
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable int status, long[] ids) {
        List<Dish> dishList = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            Dish dish = new Dish();
            dish.setStatus(status);
            dish.setId(ids[i]);
            dishList.add(dish);
        }
        dishService.updateBatchById(dishList);
        return R.success("修改状态成功");
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @Transactional
    public R<String> delete(@RequestParam List<Long> ids) {
        for (Long id : ids) {
            QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
            wrapper.eq("dish_id", id);
            dishFlavorService.remove(wrapper);

            Dish dish = dishService.getById(id);
            //清理redis缓存
            String key = "dish_" + dish.getCategoryId() + "_" + 1;
            redisTemplate.delete(key);
        }


        dishService.removeBatchByIds(ids);




        return R.success("删除成功");
    }

    /**
     * 根据种类id获取菜品
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtos = new ArrayList<>();
        //动态构造key值
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        //先从redis中获取缓存数据
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //如果存在直接返回数据
        if (dishDtos != null) {
            return R.success(dishDtos);
        }

        // 若不存在则查询数据库，将查询到的菜品数据缓存在redis中
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", dish.getCategoryId());
        List<Dish> list = dishService.list(wrapper);


        dishDtos = list.stream().map(item -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            QueryWrapper<DishFlavor> dishFlavorQueryWrapper = new QueryWrapper<>();

            dishFlavorQueryWrapper.eq("dish_id", item.getId());

            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorQueryWrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key, dishDtos, 60, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }
}
